package com.xx.pmis.web.util;

import java.awt.Color;
import java.awt.Font;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartRenderingInfo;
import org.jfree.chart.ChartUtilities;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.CategoryAxis;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.entity.StandardEntityCollection;
import org.jfree.chart.labels.ItemLabelAnchor;
import org.jfree.chart.labels.ItemLabelPosition;
import org.jfree.chart.labels.StandardCategoryItemLabelGenerator;
import org.jfree.chart.plot.CategoryPlot;
import org.jfree.chart.plot.PiePlot;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.chart.renderer.category.BarRenderer;
import org.jfree.chart.servlet.ServletUtilities;
import org.jfree.chart.title.TextTitle;
import org.jfree.data.category.CategoryDataset;
import org.jfree.data.category.DefaultCategoryDataset;
import org.jfree.data.general.DefaultPieDataset;
import org.jfree.data.general.PieDataset;
import org.jfree.ui.TextAnchor;

import com.xx.pmis.model.util.Chart;

public class BarChart {
	ChartPresent chartPresent = new ChartPresent();
	/**
	 * 饼状图
	 */
	public String generatePieChart(String title, HttpSession session, PrintWriter pw,
			int w, int h) {
		String filename = null;
		PieDataset dataset = getPieDataSet();
		JFreeChart chart = ChartFactory.createPieChart3D(title, // 图表标题
				dataset, // 数据集
				true, // 是否显示图例
				false, // 是否生成工具
				false // 是否生成URL链接
				);
		chart.setBorderVisible(false); // 边框不可见
		chart.setBorderPaint(new Color(255,0,255));

		// 乱码解决开始
		TextTitle textTitle = chart.getTitle();
		textTitle.setFont(new Font("宋体", Font.BOLD, 12)); // 标题文字乱码
		PiePlot plot = (PiePlot) chart.getPlot();
		plot.setLabelFont(new Font("宋体", Font.PLAIN, 12));// 饼上的文字乱码
		chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12)); // 图例文字乱码
		// 乱码解决结束
		
		plot.setNoDataMessage("没有数据！");
		plot.setNoDataMessagePaint(Color.blue);
		plot.setCircular(true);
		plot.setLabelGap(0.1D); // 间距
		plot.setBackgroundPaint(Color.white);
		// plot.setLabelFont(new Font("黑体", Font.TRUETYPE_FONT, 12));
		// 设定背景透明度（0-1.0之间）
		plot.setBackgroundAlpha(0.6f);
		// 设定前景透明度（0-1.0之间）
		plot.setForegroundAlpha(0.8f);

		chart.setBackgroundPaint(Color.white);
		try {
			/*------得到chart的保存路径----*/
			ChartRenderingInfo info = new ChartRenderingInfo(
					new StandardEntityCollection());
			filename = ServletUtilities.saveChartAsPNG(chart, w, h, info,
					session);
			/*------使用printWriter将文件写出----*/
			ChartUtilities.writeImageMap(pw, filename, info, true);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}

	/**
	 * 柱状图
	 */
	@SuppressWarnings("deprecation")
	public String generateBarChart(String title, HttpSession session,
			PrintWriter pw, int w, int h) {
		title = title.trim();
		String s[] = title.split("@");
		String filename = null;
		CategoryDataset dataset = getCategoryDataSet();
		JFreeChart chart = ChartFactory.createBarChart3D(s[0], // 图表标题
				s[1], // 目录轴的显示标签
				s[2], // 数值轴的显示标签
				dataset, // 数据集
				PlotOrientation.VERTICAL, // 图表方向：水平、垂直
				true, // 是否显示图例(对于简单的柱状图必须是false)
				false, // 是否生成工具
				false // 是否生成URL链接
				);
		chart.setBackgroundPaint(new Color(255, 255, 255));
		chart.setBorderVisible(false);
		CategoryPlot plot = chart.getCategoryPlot();

		CategoryAxis domainAxis = plot.getDomainAxis();// x轴
		ValueAxis numberaxis = plot.getRangeAxis(); // y轴
		plot.setForegroundAlpha(1f);

		BarRenderer barrenderer = (BarRenderer) plot.getRenderer();

		// 显示每个柱的数值，并修改该数值的字体属性
		// BarRenderer3D renderer = new BarRenderer3D();
		barrenderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
		barrenderer.setBaseItemLabelsVisible(true);
		barrenderer.setBaseFillPaint(Color.decode("#799AE1"));
		barrenderer.setMaximumBarWidth(0.03); // 设置柱状图的width

		barrenderer.setItemLabelPaint(Color.decode("#000000"));
		barrenderer.setItemLabelFont(new Font("宋体", Font.BOLD, 6));
		// 默认的数字显示在柱子中，通过如下两句可调整数字的显示
		// 注意：此句很关键，若无此句，那数字的显示会被覆盖，给人数字没有显示出来的问题
		barrenderer.setBasePositiveItemLabelPosition(new ItemLabelPosition(
				ItemLabelAnchor.OUTSIDE12, TextAnchor.BASELINE_LEFT));
		barrenderer.setItemLabelAnchorOffset(-20D);
		// 设置每个地区所包含的平行柱的之间距离
		barrenderer.setItemMargin(0.00000000003);
		// 改变柱子的颜色
		// 设置柱子宽度
		barrenderer.setMaximumBarWidth(0.0080000000000001D);
		// 设置柱子高度
		barrenderer.setMinimumBarLength(0.2);
		// 设置每个地区所包含的平行柱的之间距离
		barrenderer.setItemMargin(0.0005);

		TextTitle t = chart.getTitle();
		t.setFont(new Font("宋体", Font.BOLD, 12));// 标题文字

		domainAxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));// x轴标题文字
		domainAxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));// x轴坐标上文字
		numberaxis.setLabelFont(new Font("宋体", Font.PLAIN, 14));// y轴标题文字
		numberaxis.setTickLabelFont(new Font("宋体", Font.PLAIN, 12));// y轴坐标上文字

		chart.getLegend().setItemFont(new Font("宋体", Font.PLAIN, 12));// 图例文字

		try {
			// 得到chart的保存路径
			ChartRenderingInfo info = new ChartRenderingInfo(
					new StandardEntityCollection());
			filename = ServletUtilities.saveChartAsPNG(chart, w, h, info,
					session);
			// 使用printWriter将文件写出
			ChartUtilities.writeImageMap(pw, filename, info, true);
			pw.flush();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return filename;
	}

	/**
	 * 获取一个饼状图的简单数据集对象
	 * 
	 * @return
	 */
	private PieDataset getPieDataSet() {
		DefaultPieDataset dataset = new DefaultPieDataset();
		List<Chart> list = chartPresent.buildPieDataset();
		Iterator<?> it = list.iterator();
		while(it.hasNext()) {
			Chart chart = (Chart) it.next();
			dataset.setValue(chart.getParam1(), chart.getTotal());	
		}
		return dataset;
	}

	/**
	 * 获取一个柱状图数据集对象
	 * 
	 * @return
	 */
	private CategoryDataset getCategoryDataSet() {
		DefaultCategoryDataset dataset = new DefaultCategoryDataset();
		List<Chart> list = chartPresent.buildCategoryDataset();
		Iterator<?> it = list.iterator();
		while(it.hasNext()) {
			Chart chart = (Chart) it.next();
			dataset.addValue(chart.getTotal(), chart.getParam2(), chart.getParam1());
		}
		return dataset;
	}

}
